﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.Mvc;
using MethodWorx.Core.Validation;

namespace MethodWorx.Core.DomainModel
{
    public class BusinessRuleException : Exception
    {
        public const string NOT_UNIQUE = "Not Unique";
        public const string REQUIRED = "Required";

        public IEnumerable<ValidationError> Errors { get; set; }
        public string ModelName { get; set; }
        public string Category { get; set; }

        public BusinessRuleException(IEnumerable<ValidationError> errors)
            : this("Please correct the validation errors", errors)
        {
        }

        public BusinessRuleException(string modelName, string category)
            : this("Model Error")
        {
            this.ModelName = modelName;
            this.Category = category;
        }

        public BusinessRuleException(string message, IEnumerable<ValidationError> errors)
            : base(message)
        {
            this.Errors = errors;
        }

        public BusinessRuleException(string message)
            : this(message, new ValidationError [] { })
        {
        }

        public void AddToModelState(ModelStateDictionary ms)
        {
            if (this.Errors != null && this.Errors.Count() > 0)
            {
                foreach (ValidationError error in this.Errors)
                {
                    ms.AddModelError(error.Key, error.Message);   
                }
            }
        }

        public bool AddToValidationProvider(IValidationProvider validation)
        {
            switch (this.Category)
            {
                case NOT_UNIQUE:
                    validation.AddError(this.ModelName, "Not Unique");
                    break;
                case REQUIRED:
                    validation.AddError(this.ModelName, "Required");
                    break;
                default:
                    if (this.Errors != null && this.Errors.Count() > 0)
                    {
                        foreach (ValidationError error in this.Errors)
                        {
                            validation.AddError(error.Key, error.Message);
                        }
                    }
                    else
                        return false;
                    break;
            }

            return true;
        }
    }
}
